package cn.com.cetccst.deviceoperation;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import org.json.JSONObject;

import cn.com.cetccst.datacenter.policy.PolicyRepository;
import cn.com.cetccst.datacenter.policy.entity.PolicyEntity;
import cn.com.cetccst.mdm.MDMManager;

public class DeviceOperator {
    private static final String TAG = "DeviceOperator";
    private static DeviceOperator INSTANCE = null;

    public static DeviceOperator getInstance() {
        return INSTANCE;
    }

    private String policyPwd = "";

    public static void initialize(Context context) {
        INSTANCE = new DeviceOperator(context);
    }

    private DeviceOperator(Context context) {
//        LiveData<OperatorType> operator = OperatorManager.getInstance().getCmd();
//        operator.observeForever((this::operate));

        PolicyRepository.getInstance().getPolicy(PolicyEntity.POLICY_COMPLIANCE).observeForever((policyEntity -> {
            try {
                JSONObject root = new JSONObject(policyEntity.getContent());
                JSONObject compliance = root.optJSONObject("compliance");
                if (compliance != null) {
                    this.policyPwd = compliance.optString("deviceLockCode");
                } else {
                    this.policyPwd = "";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }));
    }

    public void operate(OperatorType type) {
        if (type == null) {
            Log.e(TAG, "can not operate type : " + type);
            return;
        }
        Log.e(TAG, "operate type : " + type);
        switch (type) {
            case RESET -> factoryReset();
            case RESTART -> restart();
            case UNREGISTER -> unregister();
            case SHUTDOWN -> shutdown();
            case LOCK_DEVICE -> lockDevice();
            case UNLOCK_DEVICE -> unlockDevice();
        }
    }

    private void unregister() {
        //TODO::注销用户
    }

    private void restart() {
        MDMManager.getInstance().getMdmEngine().reboot();
    }

    private void factoryReset() {
        MDMManager.getInstance().getMdmEngine().factoryReset();
    }

    private void shutdown() {
        MDMManager.getInstance().getMdmEngine().shutdown();
    }

    private void lockDevice() {
        if (TextUtils.isEmpty(policyPwd)) {
            Log.w(TAG, "can not lock device for NULL pwd");
        }
        MDMManager.getInstance().getMdmEngine().setDevicePassword(policyPwd);
    }

    private void unlockDevice() {
        MDMManager.getInstance().getMdmEngine().setDevicePassword("");
    }

}
